﻿// 文件使用MiniExcel源码， 使用时需遵循其 Apache License 2.0
// 修改摘要通知： 删除异步、Task等net2.0中不支持的内容，替换原先C#自带的zip处理方式，改用yacomp 进行解压缩。
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace ExcelConfig.Utils
{
    internal static class XmlReaderHelper
    {
        /// <summary>
        /// Pass &lt;?xml&gt; and &lt;worksheet&gt;
        /// </summary>
        /// <param name="reader"></param>
        internal static void PassXmlDeclarationAndWorksheet(XmlReader reader)
        {
            reader.MoveToContent();
            reader.Read();
        }

        /// <summary>
        /// e.g skip row 1 to row 2
        /// </summary>
        /// <param name="reader"></param>
        internal static void SkipToNextSameLevelDom(XmlReader reader)
        {
            while (!reader.EOF)
            {
                if (!SkipContent(reader))
                    break;
            }
        }

        //Method from ExcelDataReader @MIT License
        internal static bool ReadFirstContent(XmlReader reader)
        {
            if (reader.IsEmptyElement)
            {
                reader.Read();
                return false;
            }

            reader.MoveToContent();
            reader.Read();
            return true;
        }

        //Method from ExcelDataReader @MIT License
        internal static bool SkipContent(XmlReader reader)
        {
            if (reader.NodeType == XmlNodeType.EndElement)
            {
                reader.Read();
                return false;
            }

            reader.Skip();
            return true;
        }

        internal static bool IsStartElement(XmlReader reader, string name, params string[] nss)
        {
            if (reader == null) return false;
            foreach (var ns in nss) if (reader.IsStartElement(name, ns)) return true;
            return false;
        }

        internal static string GetAttribute(XmlReader reader, string name, params string[] nss)
        {
            string attr = default;
            foreach (var ns in nss) if ((attr = reader.GetAttribute(name, ns)) != null) return attr;
            return attr;
        }

        internal static IEnumerable<string> GetSharedStrings(Stream stream, params string[] nss)
        {
            using (var reader = XmlReader.Create(stream))
            {
                if (!IsStartElement(reader, "sst", nss))
                    yield break;

                if (!ReadFirstContent(reader))
                    yield break;

                while (!reader.EOF)
                {
                    if (IsStartElement(reader, "si", nss))
                    {
                        var value = StringHelper.ReadStringItem(reader);
                        yield return value;
                    }
                    else if (!SkipContent(reader))
                    {
                        break;
                    }
                }
            }
        }
    }
}
